<template>
	<view id="bgPage" class="bg noF">
		<view id="login">
			<view class="h3">
				烟支评吸系统-----外壳
			</view>
			<!-- <Camera></Camera> -->
			<!-- <jushi-signature :settings="settings" base64 @change="signatureChange"></jushi-signature> -->
			<image class="img" ref="imgsrc" :src="img" mode="widthFix"></image>
			<!-- <canvas canvas-id="myCanvas" ref="canvasref" style="width: 300px; height: 200px;"></canvas> -->
			<view class="card">
				<uni-forms ref="form" :modelValue="formData" :rules="rules">
					<uni-forms-item name="userName">
						<view class="input">
							<!-- <image src="../../static/if-user-alt-7.svg" mode=""></image> -->
							<uni-icons type="auth" style="font-size: 15rpx;"></uni-icons>
							<uni-easyinput class="input_" type="text" @change="change" :adjust-position="true"
								v-model="formData.userName" placeholder="请输入用户名/手机号" />
						</view>
					</uni-forms-item>
					<uni-forms-item name="passWord	">
						<view class="input">
							<uni-icons type="locked" style="font-size: 15rpx;"></uni-icons>
							<uni-easyinput class="input_" type="password" :adjust-position="true"
								v-model="formData.passWord	" placeholder="请输入8-18位密码" />
						</view>
					</uni-forms-item>
				</uni-forms>
				<button class="btn" @click="submitForm">登录</button>
				<view class="camera" @click="faceRecognition">
					<text>切换人脸识别登录</text>
				</view>
			</view>
		</view>

		<zero-loading v-if="isLoading" :mask="true"></zero-loading>
		<canvas ref="compressCanvas" style="display:none;"></canvas>
		<!-- 		<web-view src="@/components/fact.html"></web-view> -->

		<u-toast ref="uToast"></u-toast>
	</view>
</template>

<script>
	// #ifdef APP
	// import face1 from "@/uni_modules/mcc-face/index.js"
	// import face2 from "@/uni_modules/mcc-face2/index.js"
	import face from "@/uni_modules/mcc-face/index.js"

	// #endif
	// import { base64ToArrayBuffer } from '@dcloudio/uni-ui';
	import Camera from '@/components/camera/camera.vue'
	import request from '@/utils/request.js'

	import {
		loginFun
	} from "@/api/login.js"
	export default {
		data() {
			return {
				formData: {
					deviceId: Math.random(),
					userName: '',
					passWord: ''
				},
				rules: {
					userName: {
						rules: [{
							required: true,
							errorMessage: '请输入姓名',
						}]
					},
					passWord: {
						rules: [{
							required: true,
							errorMessage: '请输入密码',
						}, {
							minLength: 8,
							maxLength: 18,
							errorMessage: '密码长度在 {minLength} 到 {maxLength} 个字符',
						}]
					},
				},
				img: '',
				newImage: null,

			}
		},
		mounted() {
				console.log(11);
		},

		onLoad() {
			// this.newImage = new Image();

		},
		methods: {
			// signatureChange(e) {
			// 	this.img = e
			// },
			async faceRecognition() { //参数 a 代表 张嘴， b 代表摇头 c 代表眨眼睛 可多次重复出现， 参数为空 [] 标识 只进行人脸检测 并返回人脸数据


				// 处理转换后的图片数据，如上传等
				// 注意：这一步取决于你的具体需求

				// if (navigator.mediaDevices.getUserMedia) {
				// 	//最新标准API
				// 	navigator.mediaDevices.getUserMedia({
				// 		video: true
				// 	}).then(success => {
				// 		console.log(success);
				// 	}).catch(error => {
				// 		console.log(error);
				// 	});
				// }




				// #ifdef APP
				const letters = ['a', 'b'];
				const randomIndex = Math.floor(Math.random() * letters.length);
				console.log(letters[randomIndex]);
				let _this = this
				let isStart = false
				face.open([], async function(e) {
					// console.log(e);
					// console.log(_this.$refs.imgsrc);	


					// _this.compressBase64Image(e)







					if (!isStart) {
						isStart = true

						await request.post('/ipad/login/faceLogin', {
							baseFile: e.split(',')[1]
						}).then(res => {
							console.log('res', res);
							// console.log(!res.data);
							if (!res.data.data) {

								uni.showToast({
									title: '人脸验证不通过，请联系管理员',
									duration: 2000,
									icon: "none"
								});

							} else {
								uni.showToast({
									title: '人脸验证通过',
									duration: 2000,
								});
								setTimeout(() => {
									_this.storeLogin(res.data.data)

									// _this.$go('')
									uni.redirectTo({
										url: '/pages/index/index'
									})
								}, 500)




							}


						}).catch(err => {
							console.log(err);
						})
					}




					face.close()


				})









				// uni.chooseVideo({
				// 	sourceType:['album', 'camera'],
				// 	maxDuration: 60,
				// 	camera: 'back',
				// 	success: function(res) {
				// 		console.log('视频临时文件路径:', res.tempFilePath);
				// 		// 将视频临时文件路径传给后端
				// 		// uploadVideoToServer(res.tempFilePath);
				// 	}
				// });




				// 			face2.open().then(()=>{

				// 			    // 在这里处理的你的逻辑

				// 			    // 提供基本方法1
				// 			    face2.opendataStream((data , off) => { 
				// 					console.log(data);
				// 			        // data 返回的实时的人脸点位图  
				// 			        // off() 取消人脸点位图返回

				// 			    }) 
				// 			    // 提供基本方法2  获取截图
				// 			    // face2.getimg((img) => {_this.img = img;face2.close()})

				// 			    // 提供基本方法3 设置相机样式内容等 

				// 			    // face2.sethtml(`$('#hello').html("我看不到你的脸")`)

				// 			    // 关闭页面 

				// 			    // face2.close() 
				// 			})



				// #endif

				// #ifdef H5
				uni.showToast({
					title: 'h5端不支持人脸识别',
					duration: 2000,
					icon:"none" 
				});
 
				//#endif

			},
			async compressBase64Image(base64ImageString, maxWidth = 800, maxHeight = 600, desiredQuality = 0.8) {

				try {
					const canvas = this.$refs.compressCanvas;

					// 创建画布上下文
					const ctx = uni.createCanvasContext('compressCanvas');

					// 解析Base64数据并加载到临时Image对象
					const img = await new Promise((resolve, reject) => {

						const image = new plus.nativeObj.Image();
						image.src = base64ImageString;
						console.log(1111111111111111);
						image.addEventListener('load', () => resolve(image));
						image.addEventListener('error', (err) => reject(err));
					});

					// 计算压缩后尺寸，保持比例
					const scale = Math.min(maxWidth / img.width, maxHeight / img.height);
					const width = img.width * scale;
					const height = img.height * scale;

					// 设置画布尺寸并绘制图片
					ctx.canvas.width = width;
					ctx.canvas.height = height;
					ctx.drawImage(img, 0, 0, width, height);

					// 将压缩后的图片转为Base64数据
					await ctx.toDataURL({
						format: 'jpg',
						quality: desiredQuality,
					}).then((compressedBase64) => {
						// compressedBase64即为压缩后的Base64字符串，可以用于后续操作
						console.log('Compressed Base64:', compressedBase64);
					});
				} catch (e) {
					console.log(e);
					//TODO handle the exception
				}


			},


			submitForm() {
				// this.storeLoading(true)
				// setTimeout(()=>{
				// 	this.storeLoading(false)
				// },3000)

				// return
				if (!this.formData.userName.trim()) {
					return this.$refs.uToast.show({
						type: 'error',
						icon: false,
						title: '登陆提示',
						message: "请输入用户账号",
					})
				}

				if (!this.formData.passWord.trim()) {
					return this.$refs.uToast.show({
						type: 'error',
						icon: false,
						title: '登陆提示',
						message: "请输入密码",
					})
				}

				this.$refs.form.validate().then(e => {
					console.log('表单数据信息：', e);
					console.log('this.formData', this.formData);
					loginFun(this.formData).then(res => {
						console.log('135', res)
						if (res.code == 200) {
							console.log(res.data);
							setTimeout(() => {
								this.storeLogin(res.data)
								// this.$go('/pages/index/index')
								uni.redirectTo({
									url: "/pages/index/index"
								})
							}, 1000)
						}

					})
				}).catch(err => {
					console.log('表单错误信息：', err);
					uni.showToast({
						icon:"none",
						title:err
					})
				})
			},
			change() {
				console.log(222);
			}
		}
	}
</script>

<style lang="scss" scoped>
	.camera {
		text-align: left;
		position: relative;
		left: -20rpx;

		text {
			color: #337ecc;
		}

		margin: 30rpx 0;
		margin-bottom: 10rpx;
		font-size: 8rpx;
	}

	.h3 {
		font-size: 20rpx;
		font-weight: bold;
		text-align: center;
		line-height: 1.8;
		color: #fff;
		margin-bottom: 20rpx;
	}

	.btn {
		width: 116rpx;
		height: 26rpx;
		border-radius: 3.84rpx;
		text-align: center;
		line-height: 26rpx;
		font-size: 11rpx;
		font-weight: bold;
		color: #FFFFFF;
		background-image: url(../../static/Rectangle24.png);
		background-size: cover;
		cursor: pointer;
		margin-top: 20rpx;

		&:hover {
			opacity: 0.5;
		}


	}

	.input {
		padding: 6px 0;
		border-bottom: 1px solid #BBBBBB;
		display: flex;
		align-items: center;
		justify-content: space-between;

		.input_ {
			font-size: 11rpx;
		}

		image {
			width: 20rpx;
			height: 20rpx;
		}

		uni-easyinput {
			font-size: 30rpx;
		}
	}

	.bg {
		display: flex;
		justify-content: center;
		align-items: center;

	}

	#login {
		// height: 50%;
		width: 300rpx;
		// height: 250rpx;

		border-radius: 10rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		flex-flow: column;
		padding: 30px;
		box-sizing: border-box;

		font-size: 11rpx;
	}

	.img {
		width: 48%;
		height: 0.84%;
	}

	.card {
		width: 100%;
		box-shadow: 0px 0px 12px rgba(0, 0, 0, .12);
		// height: 100%;
		border-radius: 10rpx;
		overflow: hidden;
		display: flex;
		flex-flow: column;
		justify-content: center;
		box-sizing: border-box;
		padding: 30rpx;
		padding-bottom: 0;
		background-color: #fff;
	}
</style>